
package com.hlkj.pay.app.merchant.ext.impl.huifu.handler;
/*
 * Hlpay-Plus aggregate payment system.
 * Copyright (c) 2024-2025 Hlpay Team Copyright has the right of final interpretation.
 */

import com.hlkj.framework.common.util.json.JsonUtils;
import com.hlkj.pay.app.merchant.ext.dto.access.ChannelMerchantAccessAuthQueryContext;
import com.hlkj.pay.app.merchant.ext.dto.access.ChannelMerchantBusinessContext;
import com.hlkj.pay.app.merchant.ext.impl.huifu.dto.HuiFuConfig;
import com.hlkj.pay.app.merchant.ext.impl.huifu.handler.params.HuiFuMerchantAccessCommonParamsHandle;
import com.hlkj.pay.app.merchant.ext.impl.huifu.handler.params.HuiFuMerchantAccessCompanyParamsHandle;
import com.hlkj.pay.app.merchant.ext.impl.huifu.handler.params.HuiFuMerchantConfigParamsHandle;
import com.hlkj.pay.enums.MerchantEnum;
import com.hlkj.pay.enums.PayEnums;
import com.hlkj.pay.infrastructure.model.merchant.MerchantAccessAuthDO;
import com.hlkj.pay.infrastructure.model.merchant.MerchantAccessInfoDO;
import com.huifu.bspay.sdk.opps.client.BasePayClient;
import com.huifu.bspay.sdk.opps.core.BasePay;
import com.huifu.bspay.sdk.opps.core.config.MerConfig;
import com.huifu.bspay.sdk.opps.core.request.*;
import com.huifu.bspay.sdk.opps.core.utils.DateTools;
import com.huifu.bspay.sdk.opps.core.utils.SequenceTools;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @author HlpayTeam
 * @date 2024/09/26 10:25
 */
@Slf4j
@Repository
@RequiredArgsConstructor
@Component
public class HuiFuMerchantAccessConfigHandler extends HuiFuMerchantAccessCommonParamsHandle {

    public void subAuthQuery(ChannelMerchantAccessAuthQueryContext channelMerchantBusinessContext, String payWay) {
        HuiFuConfig huiFuConfig = huiFuConfig(channelMerchantBusinessContext.getProviderChannelConfig(), channelMerchantBusinessContext.isTest()).getData();
        // 下一步 微信配置
        MerchantAccessInfoDO merchantAccessInfoDO = channelMerchantBusinessContext.getMerchantAccessInfo();
        try {
            // 1. 数据初始化
            MerConfig merConfig = HuiFuMerchantAccessCompanyParamsHandle.merConfig(huiFuConfig);
            BasePay.initWithMerConfig(merConfig);
            // 2.组装请求参数
            V2MerchantBusiMercodeQueryRequest request = new V2MerchantBusiMercodeQueryRequest();
            // 请求日期
            request.setReqDate(DateTools.getCurrentDateYYYYMMDD());
            // 请求流水号
            request.setReqSeqId(SequenceTools.getReqSeqId32());
            // 汇付客户Id
            request.setHuifuId(merchantAccessInfoDO.getSubMchId());
            // 入驻通道类型
            request.setPayWay(payWay);
            log.info("斗拱商户AT 类型{} 查询response:{}", payWay, JsonUtils.toJsonString(request));
            // 3. 发起API调用
            Map<String, Object> aliResponse = BasePayClient.request(request, false);
            log.info("斗拱商户AT 类型{} 返回response:{}", payWay, JsonUtils.toJsonString(aliResponse));
//            // 入驻通道类型
//            request.setPayWay("W");
//            // 请求流水号
//            request.setReqSeqId(SequenceTools.getReqSeqId32());
//            log.info("斗拱商户AT微信 查询response:{}", JsonUtils.toJsonString(request));
//            // 3. 发起API调用
//            Map<String, Object> wechatResponse = BasePayClient.request(request, false);
//            log.info("斗拱商户AT微信 返回response:{}", JsonUtils.toJsonString(wechatResponse));
            HuiFuMerchantConfigParamsHandle.subAuthQueryParamsProcess(aliResponse, channelMerchantBusinessContext);

        }
        catch (Exception e) {
            e.printStackTrace();
            log.error("斗拱微信参数配置请求失败 message:{}", e.getMessage(), e);
            channelMerchantBusinessContext.setRemark("斗拱微信参数配置请求失败,失败信息" + e.getMessage());
            channelMerchantBusinessContext.setProcessStatus(Boolean.FALSE);
        }
    }

    //appid，jsapi配置
    public void wechatConfig(ChannelMerchantBusinessContext channelMerchantBusinessContext) {
        HuiFuConfig huiFuConfig = huiFuConfig(channelMerchantBusinessContext.getProviderChannelConfig(), channelMerchantBusinessContext.isTest()).getData();
        // 下一步 微信配置
        MerchantAccessInfoDO merchantAccessInfoDO = channelMerchantBusinessContext.getMerchantAccessDto().getMerchantAccessInfo();
        try {
            // 1. 数据初始化
            MerConfig merConfig = HuiFuMerchantAccessCompanyParamsHandle.merConfig(huiFuConfig);
            BasePay.initWithMerConfig(merConfig);
            // 2.组装请求参数
            V2MerchantBusiConfigRequest request = HuiFuMerchantConfigParamsHandle.v2MerchantBusiConfigRequest(huiFuConfig, channelMerchantBusinessContext);
            // 汇付客户Id
            request.setHuifuId(merchantAccessInfoDO.getSubMchId());
            // payChannelRequestDO.setAccessStatus(merchantAccessInfoDO.getStatus());
            // 3. 发起API调用
            log.info("斗拱微信参数配置请求信息response:{}", JsonUtils.toJsonString(request));
            Map<String, Object> response = BasePayClient.request(request, false);
            log.info("斗拱微信参数配置返回信息response:{}", JsonUtils.toJsonString(response));
            HuiFuMerchantConfigParamsHandle.wechatConfigParamsProcess(response, channelMerchantBusinessContext);
        }
        catch (Exception e) {
            e.printStackTrace();
            log.error("斗拱微信参数配置请求失败 message:{}", e.getMessage(), e);
            channelMerchantBusinessContext.setRemark("斗拱微信参数配置请求失败,失败信息" + e.getMessage());
            channelMerchantBusinessContext.setProcessStatus(Boolean.FALSE);
        }
    }

    /**
     * 2222
     * @param channelMerchantBusinessContext
     */
    public void wechatConfigQuery(ChannelMerchantAccessAuthQueryContext channelMerchantBusinessContext) {
        HuiFuConfig huiFuConfig = huiFuConfig(channelMerchantBusinessContext.getProviderChannelConfig(), channelMerchantBusinessContext.isTest()).getData();
        // 下一步 微信配置
        MerchantAccessInfoDO merchantAccessInfoDO = channelMerchantBusinessContext.getMerchantAccessInfo();
        try {
            // 1. 数据初始化
            MerConfig merConfig = HuiFuMerchantAccessCompanyParamsHandle.merConfig(huiFuConfig);
            BasePay.initWithMerConfig(merConfig);
            // 2.组装请求参数
            V2MerchantBusiConfigQueryRequest request = new V2MerchantBusiConfigQueryRequest();
            // 汇付客户Id
            request.setHuifuId(merchantAccessInfoDO.getSubMchId());
            // 请求流水号
            request.setReqSeqId(SequenceTools.getReqSeqId32());
            // 请求日期
            request.setReqDate(DateTools.getCurrentDateYYYYMMDD());
            // 3. 发起API调用
            Map<String, Object> response = BasePayClient.request(request, false);
            log.info("斗拱微信参数配置查询返回信息response:{}", JsonUtils.toJsonString(response));
            HuiFuMerchantConfigParamsHandle.wechatConfigQueryParamsProcess(response, channelMerchantBusinessContext);
        }
        catch (Exception e) {
            e.printStackTrace();
            log.error("斗拱微信参数配置查询请求失败 message:{}", e.getMessage(), e);
            channelMerchantBusinessContext.setRemark("斗拱微信参数配置2请求失败,失败信息" + e.getMessage());
            channelMerchantBusinessContext.setProcessStatus(Boolean.FALSE);
        }
    }

    /**
     *
     * @param channelMerchantBusinessContext
     */
    public void wechatAuth(ChannelMerchantBusinessContext channelMerchantBusinessContext) {
        HuiFuConfig huiFuConfig = huiFuConfig(channelMerchantBusinessContext.getProviderChannelConfig(), channelMerchantBusinessContext.isTest()).getData();
        // 下一步 微信认证
        MerchantAccessInfoDO merchantAccessInfoDO = channelMerchantBusinessContext.getMerchantAccessDto().getMerchantAccessInfo();
        try {
            List<MerchantAccessAuthDO> merchantAccessAuthList = channelMerchantBusinessContext.getMerchantAccessAuthList();
            // 1. 数据初始化
            MerConfig merConfig = HuiFuMerchantAccessCompanyParamsHandle.merConfig(huiFuConfig);
            BasePay.initWithMerConfig(merConfig);
            // 2.组装请求参数
            V2MerchantBusiRealnameRequest request = HuiFuMerchantConfigParamsHandle.v2MerchantBusiRealnameRequest(huiFuConfig, channelMerchantBusinessContext);
            // 汇付客户Id
            request.setHuifuId(merchantAccessInfoDO.getSubMchId());
            for (MerchantAccessAuthDO merchantAccessAuthDO : merchantAccessAuthList) {
                // 请求流水号
                request.setReqSeqId(SequenceTools.getReqSeqId32());
                Map<String, Object> channelMap = JsonUtils.parseObject(merchantAccessAuthDO.getChannelJson(), Map.class);
                String payScene;
                // 费率类型
                if (!channelMap.containsKey("payScene")) {
                    payScene = "2";
                } else
                    payScene = channelMap.get("payScene").toString();
                // 线上
                if ("4".equals(payScene) || "5".equals(payScene) || "12".equals(payScene)) {
                    request.getExtendInfos().put("pay_scene", "01");
                }
                else {
                    request.getExtendInfos().put("pay_scene", "02");
                }
                log.info("斗拱微信1认证请求参数response:{}", JsonUtils.toJsonString(request));
                // 3. 发起API调用
                Map<String, Object> response = BasePayClient.request(request, false);
                log.info("斗拱微信1认证返回信息response:{}", JsonUtils.toJsonString(response));
                HuiFuMerchantConfigParamsHandle.wechatAuthParamsProcess(response, merchantAccessAuthDO);
            }
            channelMerchantBusinessContext.setAuditStatus(MerchantEnum.CHANNEL_CONFIG_STATUS.WECHAT_AUTHING);
        }
        catch (Exception e) {
            e.printStackTrace();
            log.error("斗拱微信认证参数配置请求失败 message:{}", e.getMessage(), e);
            channelMerchantBusinessContext.setRemark("斗拱微信认证请求失败,失败信息" + e.getMessage());
            channelMerchantBusinessContext.setProcessStatus(Boolean.FALSE);
        }
    }

    /**
     * 111
     * @param channelMerchantBusinessContext
     */
    public void wechatAuthQuery(ChannelMerchantAccessAuthQueryContext channelMerchantBusinessContext) {
        HuiFuConfig huiFuConfig = huiFuConfig(channelMerchantBusinessContext.getProviderChannelConfig(), channelMerchantBusinessContext.isTest()).getData();
        try {
            List<MerchantAccessAuthDO> merchantAccessAuthDbList = channelMerchantBusinessContext.getMerchantAccessAuthDbList();
            MerConfig merConfig = HuiFuMerchantAccessCompanyParamsHandle.merConfig(huiFuConfig);
            BasePay.initWithMerConfig(merConfig);
            List<MerchantAccessAuthDO> merchantAccessAuthList = new LinkedList<>();
            channelMerchantBusinessContext.setMerchantAccessAuthList(merchantAccessAuthList);
            MerchantAccessInfoDO merchantAccessInfo = channelMerchantBusinessContext.getMerchantAccessInfo();
            // 2.组装请求参数
            V2MerchantBusiRealnameQueryRequest request = new V2MerchantBusiRealnameQueryRequest();
            // 请求日期
            request.setReqDate(DateTools.getCurrentDateYYYYMMDD());
            request.setHuifuId(merchantAccessInfo.getSubMchId());
            for (MerchantAccessAuthDO merchantAccessAuthDO : merchantAccessAuthDbList) {
                if (!PayEnums.PAY_TYPE.WECHAT.getCode().equals(merchantAccessAuthDO.getType())) {
                    continue;
                }
                // 请求流水号
                request.setReqSeqId(SequenceTools.getReqSeqId32());
                // 设置非必填字段
                Map<String, Object> extendInfoMap = new HashMap<>();
                String channelJson = merchantAccessAuthDO.getChannelJson();
                Map<String, Object> channelMap = JsonUtils.parseObject(channelJson, Map.class);
                // 费率类型
                // 费率类型
                String payScene = channelMap.get("payScene").toString();
                // 线上
                if ("4".equals(payScene) || "5".equals(payScene) || "12".equals(payScene)) {
                    request.getExtendInfos().put("pay_scene", "01");
                }
                else {
                    request.getExtendInfos().put("pay_scene", "02");
                }
                if (StringUtils.hasText(merchantAccessAuthDO.getSerialCode())) {
                    extendInfoMap.put("pay_channel_id", merchantAccessAuthDO.getSerialCode());
                } else {
                    extendInfoMap.put("pay_channel_id", huiFuConfig.getWechatChannelId());
                }
                request.setExtendInfo(extendInfoMap);
                log.info("斗拱微信认证查询请求参数response:{}", JsonUtils.toJsonString(request));
                // 3. 发起API调用
                Map<String, Object> response = BasePayClient.request(request, false);
                log.info("斗拱微信认证返回信息response:{}", JsonUtils.toJsonString(response));
                HuiFuMerchantConfigParamsHandle.wechatAuthQueryParamsProcess(response, merchantAccessAuthDO);
            }
            channelMerchantBusinessContext.setAuditStatus(MerchantEnum.CHANNEL_CONFIG_STATUS.ALIPAY_AUTH);
        }
        catch (Exception e) {
            e.printStackTrace();
            log.error("斗拱微信认证参数配置请求失败 message:{}", e.getMessage(), e);
            channelMerchantBusinessContext.setRemark("斗拱微信认证请求失败,失败信息" + e.getMessage());
            channelMerchantBusinessContext.setProcessStatus(Boolean.FALSE);
        }
    }

    /**
     *
     * @param channelMerchantBusinessContext
     */
    public void alipayAuth(ChannelMerchantBusinessContext channelMerchantBusinessContext) {
        HuiFuConfig huiFuConfig = huiFuConfig(channelMerchantBusinessContext.getProviderChannelConfig(), channelMerchantBusinessContext.isTest()).getData();
        // 下一步 支付宝认证
        MerchantAccessInfoDO merchantAccessInfoDO = channelMerchantBusinessContext.getMerchantAccessDto().getMerchantAccessInfo();
        try {
            // 1. 数据初始化
            MerConfig merConfig = HuiFuMerchantAccessCompanyParamsHandle.merConfig(huiFuConfig);
            BasePay.initWithMerConfig(merConfig);
            List<MerchantAccessAuthDO> merchantAccessAuthDbList = channelMerchantBusinessContext.getMerchantAccessAuthList();
            // 2.组装请求参数
            V2MerchantBusiAliRealnameApplyRequest request = HuiFuMerchantConfigParamsHandle.v2MerchantBusiAliRealnameApplyRequest(huiFuConfig, channelMerchantBusinessContext);
            // 汇付客户Id
            request.setHuifuId(merchantAccessInfoDO.getSubMchId());
            for (MerchantAccessAuthDO merchantAccessAuthDO : merchantAccessAuthDbList) {
                // 3. 发起API调用
                Map<String, Object> response = BasePayClient.request(request, false);
                log.info("斗拱支付宝认证返回信息response:{}", JsonUtils.toJsonString(response));
                HuiFuMerchantConfigParamsHandle.alipayAuthParamsProcess(response, merchantAccessAuthDO);
            }
            channelMerchantBusinessContext.setAuditStatus(MerchantEnum.CHANNEL_CONFIG_STATUS.ALIPAY_AUTHING);
        }
        catch (Exception e) {
            e.printStackTrace();
            log.error("斗拱支付宝认证参数配置请求失败 message:{}", e.getMessage(), e);
            channelMerchantBusinessContext.setRemark("斗拱支付宝认证请求失败,失败信息" + e.getMessage());
            channelMerchantBusinessContext.setProcessStatus(Boolean.FALSE);
        }
    }

    /**
     *
     * @param channelMerchantBusinessContext
     */
    public void alipayAuthQuery(ChannelMerchantAccessAuthQueryContext channelMerchantBusinessContext) {
        HuiFuConfig huiFuConfig = huiFuConfig(channelMerchantBusinessContext.getProviderChannelConfig(), channelMerchantBusinessContext.isTest()).getData();
        try {
            // 1. 数据初始化
            MerConfig merConfig = HuiFuMerchantAccessCompanyParamsHandle.merConfig(huiFuConfig);
            BasePay.initWithMerConfig(merConfig);
            // 2.组装请求参数
            List<MerchantAccessAuthDO> merchantAccessAuthDbList = channelMerchantBusinessContext.getMerchantAccessAuthDbList();
            V2MerchantBusiAliRealnameQueryRequest request = new V2MerchantBusiAliRealnameQueryRequest();
            // 请求日期
            request.setReqDate(DateTools.getCurrentDateYYYYMMDD());
            MerchantAccessInfoDO merchantAccessInfo = channelMerchantBusinessContext.getMerchantAccessInfo();
            request.setHuifuId(merchantAccessInfo.getSubMchId());
            for (MerchantAccessAuthDO merchantAccessAuthDO : merchantAccessAuthDbList) {
                if (!PayEnums.PAY_TYPE.ALIPAY.getCode().equals(merchantAccessAuthDO.getType())) {
                    continue;
                }
                // 请求流水号
                request.setReqSeqId(SequenceTools.getReqSeqId32());
                Map<String, Object> extendInfoMap = new HashMap<>();
                // 费率类型
                String channelJson = merchantAccessAuthDO.getChannelJson();
                Map<String, Object> channelMap = JsonUtils.parseObject(channelJson, Map.class);
                extendInfoMap.put("pay_scene", channelMap.get("payScene"));
                if (StringUtils.hasText(merchantAccessAuthDO.getSerialCode())) {
                    extendInfoMap.put("pay_channel_id", merchantAccessAuthDO.getSerialCode());
                } else {
                    extendInfoMap.put("pay_channel_id", huiFuConfig.getWechatChannelId());
                }
                request.setExtendInfo(extendInfoMap);
                log.info("斗拱支付宝认证查询请求参数response:{}", JsonUtils.toJsonString(request));
                // 3. 发起API调用
                Map<String, Object> response = BasePayClient.request(request, false);
                HuiFuMerchantConfigParamsHandle.alipayAuthQueryParamsProcess(response, merchantAccessAuthDO);
                log.info("斗拱支付宝认证查询返回信息response:{}", JsonUtils.toJsonString(response));
            }

            channelMerchantBusinessContext.setAuditStatus(MerchantEnum.CHANNEL_CONFIG_STATUS.FINISH);
        }
        catch (Exception e) {
            e.printStackTrace();
            log.error("斗拱支付宝认证查询请求失败 message:{}", e.getMessage(), e);
            channelMerchantBusinessContext.setRemark("斗拱支付宝认证查询请求失败,失败信息" + e.getMessage());
            channelMerchantBusinessContext.setProcessStatus(Boolean.FALSE);
        }
    }

}
